package gateway.mgt.api.ratelimit

import com.amihaiemil.camel.Yaml
import com.amihaiemil.camel.YamlSequenceBuilder
import gateway.mgt.api.ApiDefinition

@groovy.transform.ToString(includePackage = false, includes = ["name", "threshold"])
class SpecialUser implements ApiDefinition.Pluggable {

    RateLimitStrategy strategy
    String requestPathMatchers
    String clientId
    Long threshold

    static constraints = {
        strategy(nullable: false)
        requestPathMatchers(blank: false, display: false)
        clientId(blank: false)
        threshold(nullable: false, min: 0L)
    }

    def beforeValidate() {
        if (strategy.apiDefinitions)
            requestPathMatchers = strategy.apiDefinitions.collect { it.request.path }.join(";")
    }

    @Override
    void plug(Map<String, YamlSequenceBuilder> routeBuildElements, final ApiDefinition current) {
        def keyResolverBeanName = "specialUser_" + clientId + "_uri_" + current.request.path.replaceAll("\\*", "").replaceAll("/", "_")

        routeBuildElements.filters = routeBuildElements.filters.add(
                Yaml.createYamlMappingBuilder().add("name", "RequestRateLimiter").add("args",
                        Yaml.createYamlMappingBuilder()
                                .add("key-resolver", "\"#{@$keyResolverBeanName}\"")
                                .add("redis-rate-limiter.replenishRate", threshold as String)
                                .add("redis-rate-limiter.burstCapacity", threshold as String)
                                .build())
                        .build())
    }
}
